<?php

namespace app\api\controller;
use app\common\controller\Api;
use ApiSafety\SafetyFactory;
use think\helper\Hash;

class Index extends Api
{

    public function initialize()
    {
        parent::initialize();
    }


    /**
     * 测试用的
     * @return \think\Response
     */
    public function index()
    {
        $data = ['id' => 1];

        $result = Api::encodeData($data);
        dump($result);
        $result2 = Api::decodeData($result);
        dump($result2);
        apiRule(true, '链接成功！');
    }

    /**
     * 1、获取token access_token
     * @param appid 第三方应用唯一凭证
     * @param appsecret 第三方应用唯一凭证密钥，即appsecret
     * @return [type] [description]
     */
    public function accessToken()
    {
        $data = $this->request->param();

        if (!isset($data['appid']) || empty($data['appid'])) {
            return $this->error(false, '参数缺失', null, 10001);
        }
        /* if( !isset( $data [ 'appsecret' ] ) || empty( $data [ 'appsecret' ] )  ){
            return $this->error( false, '参数缺失' , null , 10002 );
        } */
        if ($data['appid'] != $this->appid) {
            return $this->error(false, '凭证不匹配', null, 10003);
        }
        $accessToken = base64_encode(Hash::make($this->appid . $this->appsecret));

        return $this->success(true, '成功！', $accessToken, 200);
    }

    /**
     * 2、获取jwt token
     * @param sub 面向的用户
     * @param jti 该Token唯一标识
     * @return [type] [description]
     */
    public function getToken()
    {
        $data = $this->request->param();
        if (!isset($data['sub']) || empty($data['sub'])) {
            return $this->error(false, '参数缺失', null, 10005);
        }
        if (!isset($data['jti']) || empty($data['jti'])) {
            return $this->error(false, '参数缺失', null, 10006);
        }

        // 校验jti
        if (!Hash::check($this->appid . $this->appsecret, base64_decode($data['jti']) )) {
            return $this->error(false, '凭证不匹配', null, 10003);
        }

        $data['exp'] = strtotime(date('Y-m-d 24:0:0', time())); //time()+7200
        //获取票据
        $JwtObj = SafetyFactory::factory('Jwt', $this->key);
        $jsapi_ticket = $JwtObj->getToken($data);

        return $this->success(true, '成功！', $jsapi_ticket, 200);
    }


    
}
